package hu.issue.framework.web.servlet;

import hu.issue.framework.web.Constants;
import hu.issue.framework.web.controller.Controller;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class StartupContextListener implements ServletContextListener {

	@Override
	public void contextDestroyed(final ServletContextEvent sce) {
	}

	@Override
	public void contextInitialized(final ServletContextEvent sce) {
		final ServletContext context = sce.getServletContext();
		final String controllerPackage = context.getInitParameter("controllerPackage");
		if (controllerPackage == null) {
			throw new NullPointerException("controllerPackage context parameter not set");
		}

		final ControllerLoader loader = new ControllerLoader(controllerPackage);
		Map<String, Controller> controllers;
		try {
			controllers = loader.loadControllers();
		} catch (final Exception e) {
			throw new RuntimeException(e);
		}

		final ControllerRegistry registry = new ControllerRegistry(controllers);
		context.setAttribute(Constants.REGISTRY_ATTRIBUTE, registry);
		context.setAttribute(Constants.MAPPER_ATTRIBUTE, new ControllerMapper());
		context.setAttribute(Constants.VIEWHANDLER_ATTRIBUTE, new ViewHandler());
	}
}
